package top.yqingyu.trans$client.sc.thread;

import lombok.extern.slf4j.Slf4j;
import top.yqingyu.qymsg.MsgHelper;
import top.yqingyu.qymsg.MsgTransfer;
import top.yqingyu.qymsg.MsgType;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.common.utils.ClazzUtil;
import top.yqingyu.trans$client.main.TransClient;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.transclient.sc.thread.DealMsgThread
 * @description
 * @createTime 2022年07月23日 18:06:00
 */
@Slf4j
@SuppressWarnings("all")
public record DealMsgThread(QyMsg msgHeader, TransClient client, Socket socket,
                            MsgTransfer transfer) implements Runnable {

    private static final HashMap<String, Class> Reg_Classs = new HashMap();

    @Override
    public void run() {
        log.debug("DEAL> {}", msgHeader.toString());
        AtomicReference<Class> a = new AtomicReference<>();

        try {

            if (Reg_Classs.size() == 0) {
                try {
                    List<Class<?>> classList = ClazzUtil.getClassList("top.yqingyu.trans$client.sc.command.impl", false);

                    for (Class<?> clazz : classList) {
                        Field field = clazz.getDeclaredField("commandRegx");
                        field.setAccessible(true);
                        String o = (String) field.get((Object) null);
                        Reg_Classs.put(o, clazz);
                    }
                } catch (IllegalAccessException | NoSuchFieldException e) {
                    log.error("{}", e);
                }
            }

            Reg_Classs.forEach((regx, clazzx) -> {
                if (MsgHelper.gainMsg(msgHeader).matches(regx)) {
                    a.set(clazzx);
                }
            });
        } catch (Exception e) {
            log.error("命令处理异常", e);
            throw e;
        }
        try {
            if (a.get() != null && (msgHeader.getMsgType() != MsgType.HEART_BEAT)) {
                Class clazz = (Class) a.get();
                Object o = clazz.getDeclaredConstructor().newInstance();
                Method commandDeal = clazz.getMethod("commandDeal", Socket.class, QyMsg.class);
                Object invoke = commandDeal.invoke(o, socket, msgHeader);
                log.debug("调用类: {}", clazz.getName());
            } else {
                QyMsg clone = client.clientConf.HEART_BEAT_MSG.clone();
                clone.putMsg(client.clientConf.HEART_BEAT);
                transfer.writeQyMsg(socket, clone);
            }
        } catch (Exception e) {
            log.error("命令处理异常", e);

        }
    }
}
